package com.itheima.user.services.impl;


import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.itheima.user.dto.CreateUserDto;
import com.itheima.user.dto.LoginDTO;
import com.itheima.user.dto.UpdateUserDto;
import com.itheima.user.dto.UserQueryDto;
import com.itheima.user.entity.UserRoleEntity;
import com.itheima.user.mapper.UserRoleMapper;
import com.itheima.user.vo.LoginVO;
import com.itheima.user.vo.UserVo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Service;
import com.itheima.user.services.IUserService;
import com.itheima.user.entity.UserEntity;
import com.itheima.user.mapper.UserMapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 用户表 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    @Transactional
    public int createUser(CreateUserDto createUserDTO) {

        String password = createUserDTO.getPassword();
        /**
         * BCrypt加密
         */
        String encode = BCrypt.hashpw(password, BCrypt.gensalt());
        createUserDTO.setPassword(encode);

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(createUserDTO, userEntity);
        //@TODO
        userEntity.setCreateTime(new Date());

        userMapper.insert(userEntity);

        List<UserRoleEntity> list = new LinkedList<>();

        for (Long roleId : createUserDTO.getRoleIds()) {
            UserRoleEntity userRoleEntity = new UserRoleEntity();
            System.out.println(userEntity.getId());
            userRoleEntity.setUserId(userEntity.getId());
            Integer i = roleId.intValue();
            System.out.println( i);
            userRoleEntity.setRoleId(i);
            list.add(userRoleEntity);
        }
        System.out.println(list);
        int i = userRoleMapper.insertBatch(list);

        return i;
    }
    //登录认证功能
    @Override
    public LoginVO login(LoginDTO loginDTO) {
        QueryWrapper wrapper =new QueryWrapper();
        wrapper.eq(UserEntity::getUsername,loginDTO.getUsername());
        UserEntity userEntity = userMapper.selectOneByQuery(wrapper);
        if(userEntity == null){
            throw new RuntimeException("账号不存在");
        }
        if(!BCrypt.checkpw(loginDTO.getPassword(),userEntity.getPassword())){
            throw new RuntimeException("密码错误");
        }
        LoginVO loginVO = new LoginVO();
        StpUtil.login(userEntity.getPassword(),userEntity.getUsername());
        String tokenValue = StpUtil.getTokenValue();
        loginVO.setToKen(tokenValue);
        loginVO.setUser(userEntity);
        return loginVO;
    }
    @Override
    public void updateUser(UpdateUserDto updateUserDto) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(updateUserDto,userEntity);
        QueryWrapper wrapper = new QueryWrapper();
        QueryWrapper eq = wrapper.eq("id", updateUserDto.getUserId());
        userMapper.updateByQuery(userEntity,eq);
        userRoleMapper.deleteByQuery(wrapper);
        List<UserRoleEntity> userRoleEntities = new LinkedList<>();
        for (Long roleId : updateUserDto.getRoleIds()) {
            UserRoleEntity userRoleEntity = new UserRoleEntity();
            userRoleEntity.setUserId(updateUserDto.getUserId());
            Integer i = roleId.intValue();
            userRoleEntity.setRoleId(i);
            userRoleEntities.add(userRoleEntity);
        }
        userRoleMapper.insertBatch(userRoleEntities);
    }

    @Override
    public void deleteUser(Long id) {
        Object loginId = StpUtil.getLoginId();
        System.out.println(loginId);
        if(loginId.equals(id)){
            throw new RuntimeException("不能删除自己");
        }
        userMapper.deleteById( id);
        StpUtil.kickout(id);
    }
    @Override
    //分页查询
    public Page<UserVo> pageList(UserQueryDto userQueryDto) {
        if (userQueryDto.getPage() == null) {
            userQueryDto.setPage(1);
        }
        if (userQueryDto.getSize() == null) {
            userQueryDto.setSize(10);
        }

        QueryWrapper wrapper = new QueryWrapper();
        if(!StringUtils.isEmpty(userQueryDto.getUsername())) {
            wrapper.like(UserEntity::getUsername, userQueryDto.getUsername());
        }
        if(!StringUtils.isEmpty(userQueryDto.getRealName())) {
            wrapper.like(UserEntity::getRealName, userQueryDto.getRealName());
        }
        if(userQueryDto.getDeptId() != null) {
            wrapper.eq(UserEntity::getDeptId, userQueryDto.getDeptId());
        }

        if(userQueryDto.getStatus() != null) {
            wrapper.eq(UserEntity::getStatus, userQueryDto.getStatus());
        }
        Page<UserEntity> paginate = userMapper.paginate(userQueryDto.getPage(), userQueryDto.getSize(), wrapper);
        Page<UserVo> userEntityPage = new Page<>();
        BeanUtils.copyProperties(paginate, userEntityPage);
        return userEntityPage;
    }
}